import React from 'react';
import {useDispatch } from 'react-redux'

  
function PubSend(prop) {

  const dispatch = useDispatch()  

  const uri = 'ws://chat.helapu.com/chat/' + localStorage.getItem('token')

  console.log("ws: " + uri);
  
  if (global.ws === undefined) {

    console.log("ws is undefined");
    
    const ws = new WebSocket(uri);

    ws.onopen = function() {
      console.log("in ws onopen");
    }

    ws.onmessage = function(msg) {
      
      console.log("onmessage " + msg.data);

      let data = JSON.parse(msg.data)

      let item = {
        messageId: data['messageId'],
        roomId: data['roomId'],
        from: data['from'],
        to: data['to'],
        payload: data['payload']
      }

      dispatch({
        type: "ADD_CHAT",
        payload: item
      })
      
    }

    ws.onclose = function() {
      console.log("onclose")
    }

    global.ws = ws
  }

  return (
    <div className="w-0 h-0">
      u
    </div>
  )

}

export default PubSend
